package com.ark.controller.common;

import com.ark.common.constant.Constants;
import com.ark.common.response.Result;
import com.ark.common.utils.RedisUtils;
import com.ark.security.service.MailService;
import com.ark.service.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import java.util.Random;

@Slf4j
@RestController
public class CaptchaController {

    @Resource
    private MailService mailService;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private SysUserService userService;

    private final Random random = new Random();

    @PostMapping("/sendEmail")
    public Result sendEmail(String email){
        if (StringUtils.isEmpty(email)) {
            return Result.warn("邮箱不能为空!");
        }
        if (!email.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
            return Result.warn("邮箱格式不正确!");
        }
        if (userService.emailExist(email)){
            return Result.warn("邮箱已注册!");
        }
        if (redisUtils.hasKey(Constants.REGISTER_USER_KEY+email)) {
            return Result.warn("发送过于频繁,请三分钟后重试!");
        }
        int code = random.nextInt(999999);
        mailService.sendHtmlTextMailCode(email, String.format("%06d",code));
        redisUtils.setCacheObject(Constants.REGISTER_USER_KEY+email,code,3,java.util.concurrent.TimeUnit.MINUTES);
        return Result.success();
    }
}
